﻿
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Domain;
using Data.Utils;

namespace Data.Repositories
{
    public class UserRepository
    {
        ModeloCantinhoContainer ctx = new ModeloCantinhoContainer();

        public void Add(User user)
        {
            ctx.User.AddObject(user);
            ctx.ObjectStateManager.ChangeObjectState(user, System.Data.EntityState.Added);
            SaveChanges();
        }

        public void Update(User user)
        {
            try
            {
                ctx.User.Attach(user);ctx.ObjectStateManager.ChangeObjectState(user, System.Data.EntityState.Modified);
            }
            catch (Exception)
            {
                //controlar os erros
            }
            finally
            {
                
                SaveChanges();
            }
            
        }

        public User GetUserByUserName(string username)
        {
            return null;
        }

        public User GetNew()
        {
            return new User();
        }

        public User GetUserByUserID(int userid)
        {
            return ctx.User.FirstOrDefault(x=>x.Id == userid);
        }

        public User GetUserByEmail(string email)
        {
            return ctx.User.FirstOrDefault(x => x.Email.ToUpper() == email.ToUpper());
        }

        public User GetUserByEmail_Aprovado(string email)
        {
            return ctx.User.FirstOrDefault(x => x.Email.ToUpper() == email.ToUpper() && x.IsApproved);
        }

        public string GetUserFotoByEmail(string email)
        {
            User user = ctx.User.FirstOrDefault(x => x.Email.ToUpper() == email.ToUpper() && x.IsApproved);

            if (user != null)
            {
                if(string.IsNullOrEmpty(user.Foto))
                    return "content/images/anonM.gif";
                else
                    return user.Foto;
            }
            else return "content/images/anonM.gif";
        }

        public void Delete(User user)
        {
            ctx.User.DeleteObject(user);
            ctx.ObjectStateManager.ChangeObjectState(user, System.Data.EntityState.Deleted);
            SaveChanges();
        }

        public List<User> FindAllUsers()
        {
            //return All().ToList();
            return ctx.User.ToList();
        }

        public int GetNumberOfUsersOnline()
        {
            return ctx.User.Count(x => x.IsOnLine.HasValue && x.IsOnLine.Value);
        }

        public List<User> FindMatchingUsers(string usernameToMatch)
        {
            //IQueryable<User> query = from users in Repository.Repo.All<User>() where users.UserName.Contains(usernameToMatch) select users;
            //return query.ToList();
            return null;
        }

        public List<User> FindMatchingEmails(string emailToMatch)
        {
            return ctx.User.Where(x => x.Email.ToUpper() == emailToMatch.ToUpper()).ToList();
        }

        public int EmailDisponivel(string email)
        {
            return ctx.User.Count(x => x.Email.ToUpper() == email.ToUpper()) == 0 ? 0 : 1;
        }

        public void AssociarUserNewsletter(User user ,List<int> NewsletterIds)
        {
            NewsletterRepository news = new NewsletterRepository();
            foreach (int item in NewsletterIds)
            {
                user.Newsletter.Add(news.GetById(item));
            }
        }

        public void InsertUserRegisto(string email,string lastloginip,bool soupai,string emailParceiro,bool tentarengravidar,List<int> Newsletter,List<Filho> filhos,string foto)
        {
            User user = GetUserByEmail(email);
            user.LastLoginIP = lastloginip;
            user.Genero = soupai ? "M" : "F";
            user.EmailParceiro = emailParceiro;
            user.EmailKey = MailTools.GenerateKey();
            string path = @"Content/Images/FotosUser/";
            if (foto != null)
                user.Foto = path + foto;
            else 
            {
                if(user.Genero == "M")
                    user.Foto = path + "anonM.gif";
                else
                    user.Foto = path + "helloKit.png";
            }
            if (!tentarengravidar)
            {
                foreach (Filho item in filhos)
	            {
                    item.Activo = true;
                    item.DataFormatada = item.DataNascimento.ToLongDateString();
                    item.DataInserido = DateTime.Now;

                    if (item.Foto != null)
                        item.Foto = path + item.Foto;
                    else
                    {
                        if (item.Genero == "M")
                            item.Foto = path + "miudo.png";
                        else
                            item.Foto = path + "helloKit.png";
                    }

                    user.Filho.Add(item);
	            }
                
                //user.Filho.Add(new Domain.Filho
                //{
                //    Activo = true,
                //    DataNascimento = DatanascimentoBebe.Value,
                //    Genero = generoBebe,
                //    Nome = nomeBebe,
                //    DataFormatada = DateTime.Now.ToLongDateString()
                //});
            }

            //AssociarUserNewsletter(user, Newsletter);
            //Update(user);
            SaveChanges();

            //Enviar email
            MailTools.EnviaMailRegisto(user);

        }

        public bool ActivateUser(string username, string key)
        {
            var dbuser = GetUserByEmail(username);

            if (dbuser.EmailKey == key)
            {
                dbuser.IsApproved = true;
                dbuser.LastActivityDate = DateTime.Now;
                //dbuser.EmailKey = null;
                SaveChanges();
                return true;
            }
            else
            {
                return false;
            }
        }

        public void SaveChanges()
        {
            try
            {
                ctx.SaveChanges();
            }
            catch (Exception)
            {
                throw;
            }
        }


        public void GravaPontos(PontosRepository.TipoPonto tipoPonto,User user)
        {
            PontosRepository repPonto = new PontosRepository();
            if(user.Ponto != null)
                user.Ponto = repPonto.UpdatePonto(tipoPonto,user.Ponto);
            else
                user.Ponto = repPonto.Createponto(tipoPonto);
            Update(user);
        }
    }
}
